package cn.edu.csmzxy.rk233x.auth_system.exception;

/**
 * @author wumxing
 * @date 2025/10/15 9:56
 * @description
 */
import cn.edu.csmzxy.rk233x.auth_system.dto.ResultDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@Slf4j
@RestControllerAdvice  // 全局异常处理（针对RestController）
public class GlobalExceptionHandler {
    // 处理参数校验失败异常（@Valid触发）
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResultDTO<?> handleValidException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        FieldError fieldError = bindingResult.getFieldError();
        String message = fieldError != null ? fieldError.getDefaultMessage() : "参数校验失败";
        log.error("参数校验异常：{}", message);
        return ResultDTO.fail(400, message);
    }
    // 处理自定义业务异常
    @ExceptionHandler(BusinessException.class)
    public ResultDTO<?> handleBusinessException(BusinessException e) {
        log.error("业务异常：{}", e.getMessage());
        return ResultDTO.fail(e.getCode(), e.getMessage());
    }
    // 处理其他未知异常
    @ExceptionHandler(Exception.class)
    public ResultDTO<?> handleException(Exception e) {
        log.error("系统未知异常：", e);
        return ResultDTO.fail(500, "系统异常："+e.getMessage());
    }
}